package com.core;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;
import java.util.Map;

import com.core.initialize.AbsChannelInitializer;
import com.core.initialize.ServerHttpInitializer;
import com.core.rest.AbstractHttpHandler;

/**
 * http服务器监听
 * @author King
 *
 */
public class HttpAcceptor
{
	private EventLoopGroup bossGroup;
	private EventLoopGroup workerGroup;
	private ServerBootstrap b;
	private Channel channel;
	
	//private static Map<String,AbstractHttpHandler>httpHandlers;
	
	public HttpAcceptor(EnginService engin,InetSocketAddress address,Map<String,AbstractHttpHandler>handlers)
	{
	    
	    
		AbsChannelInitializer handler = new ServerHttpInitializer(handlers);
		handler.setEnginService(engin);
		// handler
		this.bossGroup = new NioEventLoopGroup();
		this.workerGroup = new NioEventLoopGroup();
		this.b = new ServerBootstrap();
		b.option(ChannelOption.SO_BACKLOG, 1024);
		b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
				.childHandler(handler);
		try {
			this.channel = b.bind(address).channel();
		} catch (Exception e) {
			e.printStackTrace();
			 this.workerGroup.shutdownGracefully();
	         this.bossGroup.shutdownGracefully();
		}
	}
	
	public static void main(String[] args)
	{
		InetSocketAddress address = new InetSocketAddress("127.0.0.1", 7777);
		//new HttpAcceptor(null, address,HttpController.handlers);
	}
	
	
	/**
	 * 关闭服务器用
	 */
	public void shutdown()
	{
		this.channel.close();
		this.workerGroup.shutdownGracefully();
        this.bossGroup.shutdownGracefully();
	}

	public Channel getChannel() {
		return channel;
	}
	
	private void initHandlers(){
	    
	}

}
